package net

import (
	"fmt"
	"os"

	"github.com/nknorg/nkn/v2/api/httpjson/client"
	nknc "github.com/nknorg/nkn/v2/cmd/nknc/common"

	"github.com/urfave/cli"
)

func netAction(c *cli.Context) (err error) {
	if c.NumFlags() == 0 {
		cli.ShowSubcommandHelp(c)
		return nil
	}
	addr := c.String("addr")

	var resp []byte
	var output [][]byte
	resp, err = client.Call(nknc.Address(), "join", 0, map[string]interface{}{"addr": addr})
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		return err
	}
	output = append(output, resp)

	for _, v := range output {
		nknc.FormatOutput(v)
	}

	return nil
}

func NewCommand() *cli.Command {
	return &cli.Command{
		Name:        "net",
		Usage:       "网络层命令",
		Description: "",
		ArgsUsage:   "[args]",
		Flags: []cli.Flag{
			cli.StringFlag{
				Name:  "addr, a",
				Usage: "hash for querying a block",
			},
		},
		Action: netAction,
		OnUsageError: func(c *cli.Context, err error, isSubcommand bool) error {
			nknc.PrintError(c, err, "net")
			return cli.NewExitError("", 1)
		},
	}
}
